import { ajaxAsync } from 'vue-xiaobu-utils'
import NoticeModel from './NoticeModel'

const BUS_NOTICE_CACHE_KEY = 'LineNoticeListModule28307hkw'

/**
 * 获取线路公告列表
 * @param {Function} callback 缓存和协议成功的回调函数
 */
function getBusLineNoticeList(callback) {
  // /bus/notice/latest/list
  let postData = {
    // PAGE_INDEX: 1,
    // PAGE_CAPACITY: 3
  }
  return ajaxByCache(
    BUS_NOTICE_CACHE_KEY,
    res => {
      let list = []
      if (res.COUNT > 0 && res.LIST.length > 0) {
        res.LIST.map(item => {
          let noticeModel = new NoticeModel(
            item.NOTICE_ID,
            item.NOTICE_TITLE,
            item.NOTICE_CONTENT,
            item.NOTICE_TIME
          )
          list.push(noticeModel)
        })
        callback(list)
      } else {
        callback(list)
      }
    },
    '/bus/notice/latest/list',
    postData
  )
}

/**
 *
 * @param {String} cacheKey 缓存的key
 * @param {Function} cacheCallback 缓存和协议成功的回调函数
 * @param {String} urlString
 * @param {Object} sendObj
 * @param {Number} autoExLvl
 */
async function ajaxByCache(
  cacheKey,
  cacheCallback,
  urlString,
  sendObj,
  autoExLvl = 0
) {
  // 先获取缓存数据，将缓存数据返回
  let cacheValue = localStorage.getItem(cacheKey)
  if (cacheCallback && cacheValue) {
    cacheCallback(JSON.parse(cacheValue))
  }
  let res = await ajaxAsync(urlString, sendObj, autoExLvl)
  let resString = JSON.stringify(res)
  if (resString !== cacheValue) {
    // 如果协议返回和缓存不一致则更新缓存并返回新数据
    localStorage.setItem(cacheKey, resString)
    cacheCallback(res)
  }
  return true
}

export { getBusLineNoticeList }
